import {
  EllipsisOutlined,
  PlusOutlined,
  InboxOutlined,
  FolderOutlined,
} from '@ant-design/icons'
import type { ActionType, ProColumns } from '@ant-design/pro-components'
import { ProTable, TableDropdown } from '@ant-design/pro-components'
import {
  Button,
  Divider,
  Dropdown,
  message,
  Popconfirm,
  Select,
  Space,
  Tag,
  Upload,
} from 'antd'
import fileIcon from '../../../public/icon/file.png'
import folderIcon from '../../../public/icon/folder.png'
import { useEffect, useRef, useState } from 'react'
import request, { fetch } from 'umi-request'
import CreateForm from '@/assets/components/CreateForm'
import UploadForm from '@/assets/components/uploadForm'
import {
  deleteFile,
  getImage,
  postFileList,
  updateFile,
} from '@/services/files'
import { PopconfirmProps, UploadProps, Image } from 'antd'
import { isString } from 'antd/es/button'
import { allLabel, deleteLabel } from '@/services/labels'
import FetchImage from '@/assets/components/GetImage'
import PreviewImage from '../Table/PreviewImage'
const { Dragger } = Upload
const { Option } = Select
export default () => {
  const [parentId, setParentId] = useState(2)
  const [pathArr, setPathArr] = useState([])
  const [pageSize, setPageSize] = useState(10)
  const actionRef = useRef<ActionType>()
  const [dataSource, setDataSource] = useState([])
  const [visibleFetchImg, setVisibleFetchImg] = useState(false)
  const [fileId, setFileId] = useState(2)
  const [labelList, setLabelList] = useState([])

  //获取label列表
  const labelArr = async () => {
    let result = await allLabel({ pageSize: 1000, current: 1 })
    if (result.code === 200) {
      console.log(result?.data?.records)
      setLabelList(
        result?.data?.records?.map((item) => {
          return { value: item.id, label: item.name }
        })
      )
    }
  }
  useEffect(() => {
    labelArr()
  }, [])

  //查看文件或文件夹
  const checkFile = (props: any) => {
    setParentId(props?.id)
    let pathList = [...pathArr, parentId]
    setPathArr(pathList)
    actionRef.current?.reload()
  }

  const confirm: PopconfirmProps['onConfirm'] = async (values) => {
    await deleteFile({ filesId: values?.id })
    actionRef.current?.reload()
    message.success('Click on Yes')
  }

  const cancel: PopconfirmProps['onCancel'] = (e) => {
    message.error('Click on No')
  }

  const columns: ProColumns[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '图片',
      width: '5vw',
      editable: false,
      hideInSearch: true,
      render: (_, record) => (
        <>
          {(record.type !== null || record.type !== '') &&
          (record?.type?.toLowerCase() === '.png' ||
            record?.type?.toLowerCase() === '.jpg' ||
            record?.type?.toLowerCase() === '.jpeg' ||
            record?.type?.toLowerCase() === '.tif') ? (
            <Image src={`/api/${record.netPath}`} />
          ) : record.type?.toLowerCase() === '.dng' ? (
            <Image src={fileIcon} />
          ) : (
            <Image src={folderIcon} />
          )}
        </>
      ),
    },
    {
      title: '标题',
      dataIndex: 'name',
      editable: false,
      key: 'name',
      width: '20vw',
      // copyable: true,
      ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
      render: (_, record) => (
        console.log(record),
        (
          <Space>
            {!(
              record?.type?.toLowerCase() === '.png' ||
              record?.type?.toLowerCase() === '.jpg' ||
              record?.type?.toLowerCase() === '.jpeg' ||
              record?.type?.toLowerCase() === '.tif'
            ) ? (
              <a
                onClick={() => {
                  setFileId(record.id)
                }}>
                {record?.name}
              </a>
            ) : (
              // <a onClick={() => checkFile(record)}>{record?.name}</a>
              <PreviewImage name={record.name} url={record.netPath} />
            )}
          </Space>
        )
      ),
    },
    {
      title: '文件类型',
      dataIndex: 'type',
      width: '5vw',
      editable: false,
      hideInSearch: true,
    },
    {
      disable: true,
      title: '标签1',
      width: '25vw',
      dataIndex: 'labelList',
      search: false,
      renderFormItem: (_, { defaultRender, record }) => {
        // 将当前记录的标签转换为数组形式
        const initialLabels = record.labels
          ? record.labels.map((label) => label?.id) // Use id if labelList uses id
          : []
        console.log(record.labels, initialLabels)

        return (
          <Select
            mode="multiple"
            style={{ width: '100%' }}
            placeholder="选择标签"
            options={labelList}
            // defaultValue={initialLabels}
            onChange={(value) => {
              // 这里可以处理标签选择的变化
              console.log(value)
            }}></Select>
        )
      },
      render: (_, record) => {
        let labels = record?.labels

        if (labels?.length > 4) {
          labels = labels.slice(0, 4)
          labels.push({
            label: '...',
            name: '...',
          })
        }
        return record.labels == null ? (
          <div></div>
        ) : (
          <Space>
            {labels.map(({ name, color }) => (
              <Tag color={color} key={name}>
                {name}
              </Tag>
            ))}
          </Space>
        )
      },
    },
    {
      title: '标签',
      dataIndex: 'label',
      hideInTable: true,
      valueType: 'select', // Change valueType to select for multi-select
      fieldProps: {
        mode: 'multiple', // Enable multiple selection
        showSearch: true, // Enable search functionality
      },
      request: async () => {
        const result = await allLabel({ pageSize: 1000, current: 1 })
        // Assuming `result.data` contains the array of options in the required format
        // If the result structure is different, adjust accordingly
        return (
          result?.data?.records.map((item) => ({
            value: item.id, // Assuming each item has a unique identifier 'id'
            label: item.name, // Assuming each item has a 'name' for display
          })) || [
            { value: '520000201604258831', label: 'Patricia Lopez' },
            { value: '520000198509222123', label: 'Jose Martinez' },
          ]
        )
      },
    },
    {
      title: '拍摄时间',
      key: 'createTime',
      dataIndex: 'createTime',
      valueType: 'date',
      width: '200px',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '拍摄时间',
      dataIndex: 'created_at',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            beginTime: value[0],
            endTime: value[1],
          }
        },
      },
    },
    {
      title: '操作',
      width: '15vw',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          href={record.url}
          target="_blank"
          rel="noopener noreferrer"
          key="view"
          onClick={() => {
            record?.isFolder ? checkFile(record) : null
          }}>
          {record?.isFolder ? '进入' : ''}
          {/* {record?.isFolder ? '进入' : '查看'} */}
        </a>,
        <Divider type="vertical" />,
        <a
          key="edit"
          onClick={() => {
            action?.startEditable?.(record.id)
          }}>
          编辑
        </a>,
         <Divider type="vertical" />,
         <a
         key="edit"
         onClick={() => {
          window.open(`http://j9tynr.natappfree.cc/file/download/${record.id}`)
         }}>
         下载
       </a>,
        <Divider type="vertical" />,
        <Popconfirm
          // title="Delete the task"
          description="是否确定删除"
          onConfirm={() => confirm(record)}
          onCancel={cancel}
          okText="确定"
          cancelText="取消">
          <a target="_blank" rel="noopener noreferrer" key="delete">
            删除
          </a>
        </Popconfirm>,
      ],
    },
  ]

  return (
    <>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        cardBordered
        dataSource={dataSource}
        request={async (params, sort, filter) => {
          //同时查询文件列表
          const result = await postFileList({ parentId: parentId, ...params })
          setDataSource(result?.data?.records)
          console.log(params)

          return {
            data: result?.data?.record,
            total: result.data.total,
            success: result?.success,
          }
        }}
        editable={{
          type: 'multiple',
          onSave: async (rowKey, record) => {
            // 这里编写发送请求的逻辑，等待完善
            console.log(record)

            const response = await updateFile(record)
            if (response.success) {
              // 请求成功，更新状态或提示用户
              actionRef.current?.reload()
              message.success('保存成功')
            } else {
              // 处理错误情况
              actionRef.current?.reload()
              message.error('保存失败')
            }
          },
          onDelete: async (rowKey, record) => {
            const response = await deleteFile({ filesId: record?.id })
            if (response.success) {
              // 请求成功，更新状态或提示用户
              actionRef.current?.reload()
              message.success('删除成功')
            } else {
              // 处理错误情况
              actionRef.current?.reload()
              message.error('删除失败')
            }
          },
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
          onChange(value) {
            console.log('value: ', value)
          },
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          // span: ,
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        form={{
          // 由于配置了 transform，提交的参数与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              }
            }
            return values
          },
        }}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        dateFormatter="string"
        // headerTitle="高级表格"
        toolBarRender={() => [
          parentId == 2 ? null : (
            <a
              onClick={() => {
                let newParentId = pathArr.pop()
                setParentId(newParentId)
                let newPathList = pathArr
                setPathArr(newPathList)
                actionRef.current?.reload()
              }}>
              返回上一层
            </a>
          ),
          <CreateForm parentId={parentId} actionRef={actionRef} />,
          <UploadForm parentId={parentId} actionRef={actionRef} />,
        ]}
      />
    </>
  )
}
